<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/2
 * Time: 17:26
 */
namespace app\online\controller;


use think\Db;
use think\Loader;
use think\Session;

class Index extends Common
{
	//判断是否登录
	public function _initialize()
	{
		parent::_initialize();
	}
	
	/**
	 * 一键代发首页
	 * @param string get.title 要检索的字段
	*/
	public function index()
	{
		$where = ['query'=>[]];
		$db = Db::table('business')->where('status',2);
		if(!empty(trim(input('get.title')))){
			$title = trim(input('get.title'));
			$db->where('linkman|telephone','like',"%{$title}%");
			$where['query']['title'] = $title;
		}
		$result = $db->order('id desc')->paginate(8,false,$where);
		return view('index',compact('result'));
	}
	/**
	 * 查看商家商品
	 * @param string get.bid 商家id
	*/
	public function goods()
	{
		$where = ['query'=>[]];
		$bid = input('get.bid');
		$where['query']['bid'] = $bid;
		$db = Db::table('product')->where('type',2)->where('bid',$bid);
		if(!empty(trim(input('get.title')))){
			$title = trim(input('get.title'));
			$db->where('pname|barcode','like',"%{$title}%");
			$where['query']['title'] = $title;
		}
		$result = $db->paginate(8,false,$where);
		return view('goods',compact('result','bid'));
	}
	/**
	 * 购物车
	 * @param json  post.data 商品id;
	*/
	public function shopping()
	{
		try{
			Db::startTrans();
			$data = json_decode(input('post.data'));
			$input['bid'] = input('post.bid');
			$input['aid'] = Session::get('adminuser.id');
			for($i=0;$i<count($data);$i++){
				//判断是否已经购买
				$number = Db::table('shopping')->where('pid',$data[$i])->where('aid',Session::get('adminuser.id'))->where('status',1)->value('number');
				if($number != null){
					//如果购买+1
					$number += 1;
					Db::table('shopping')->where('pid',$data[$i])->where('aid',Session::get('adminuser.id'))->where('status',1)->update(['number'=>$number]);
				}else{
					$input['pid'] = $data[$i];
					Db::table('shopping')->insertGetId($input);
				}
			}
			Db::commit();
			$success = ['success'=>'添加成功'];
			return json($success);
		}catch (\PDOException $e){
			Db::rollback();
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
	
	/**
	 * 下架
	 * @param string post.id 商品id
	*/
	public function remove()
	{
		try{
			$id = input('post.id');
			$result = Db::table('product')->where('id',$id)->update(['type'=>1]);
			if(!$result){
				throw new \PDOException('操作失败');
			}
			$success = ['success'=>'操作成功'];
			return json($success);
		}catch (\PDOException $e){
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
}